/**
 * Created by kongwentao on 2016/11/1.
 */
import MapXMLHttpRequest from "http://minedata.cn/minemapapi/demo/js/MapXMLHttpRequest.js"

'use strict';

function PatrolRoutePlanTool(map){
  this.myHttp = new MapXMLHttpRequest()

  this.point_line_geojson = {"type": "FeatureCollection", "features": []}
  this.linestring = {"type": "Feature", "geometry": {"type": "LineString", "coordinates": []}}
  this.map = map
}

PatrolRoutePlanTool.prototype.getDistance = function(){
  return this.distanceSum
}

/**
 * 获取两点之间的行驶路径
 * @param sPoint 起点经纬度 ：“经度,纬度”
 * @param ePoint 终点经纬度 ： 同上
 * @param wayPoints 途经点的经纬度：默认为无
 */
PatrolRoutePlanTool.prototype.getRoute = function(sPoint,ePoint,wayPoints) {
  var url_head = "http://123.207.124.207:8084/minemap-server/service/route/driving?&token=123444&"
  // sPoint=109.83611583709717,40.607355154008985
  // &ePoint=109.86656427383423,40.65546781426045
  // &wayPoints=109.82500076293945,40.6212168482447
  var costModel=32 // 不考虑动态交通的最短距离
  var url = url_head+"sPoint="+sPoint+"&ePoint="+ePoint+"&wayPoints="+wayPoints+"&costModel="+costModel
  myHttp.send("GET", url, '', callback, null)

}


PatrolRoutePlanTool.prototype.callback = function(responseText, responseXML) {
  //{"errcode":0,"errmsg":null,"data":{"pageCount":0,"totalCount":0,"pageNumber":0,"rows":[]}}
  var searchResult = {}
  if (responseText.length > 1) {
    searchResult = JSON.parse(responseText)
    if (searchResult.errcode == 0 && searchResult.data.rows.length > 0) {
      console.log("get call back")
      console.log(searchResult)
      var resGeojson = translateRes2Geojson(searchResult)
      console.log(resGeojson)
    }
  }
}


PatrolRoutePlanTool.prototype.translateRes2Geojson = function(response) {
  response.data.rows[0].segmt.forEach(function (line) {
    var lineSegment = {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": []
      },
      "properties": {
        "roadName":'',
        "dist":'',
        "distUnit":''
      }
    }

    lineSegment.geometry = line.clist.geometry
    lineSegment.properties.roadName = line.roadName
    lineSegment.properties.dist = line.dist.dist
    lineSegment.properties.distUnit = line.dist.unit
    poi.properties = point;
    route_geojson.data.features.push(lineSegment)

    return lineSegment
  })

  return route_geojson
}

PatrolRoutePlanTool.prototype.replan_route = function() {


  if(this.route_geojson.data.features.length>1){
    for(var i=0; i<this.route_geojson.features.length; i++){
      var startPoint = this.route_geojson.data.features[i].geometry.coordinates
      var endPoint = this.route_geojson.data.features[i+1].geometry.coordinates
      getRoute(startPoint,endPoint)
    }
  }
}
